package com.hulk.dryad.admin.controller.gen;

import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hulk.dryad.admin.api.vo.gen.GenConfVO;
import com.hulk.dryad.admin.mapstruct.GenConfStruct;
import com.hulk.dryad.common.annotation.Idempotent;
import com.hulk.dryad.common.component.R;
import com.hulk.dryad.persistence.entity.GenConfModel;
import com.hulk.dryad.admin.service.GenTableColumnService;
import com.hulk.dryad.admin.service.GeneratorService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

/**
 * 代码生成器
 *
 * @author kim
 * @date 2018-07-30
 */
@Api(value = "genCode", tags = "表单管理")
@RestController
@RequiredArgsConstructor
@RequestMapping("/admin/gen/generator")
public class GeneratorController {

	private final GeneratorService generatorService;

	private final GenTableColumnService columnService;

	/**
	 * 列表
	 * @param tableName 参数集
	 * @param dsName 数据源编号
	 * @return 数据库表
	 */
	@ApiOperation(value = "getPage", notes = "数据源分页")
	@GetMapping("/page")
	public R getPage(Page page, String tableName, String dsName) {
		return R.ok(generatorService.getPage(page, tableName, dsName));
	}

	/**
	 * 预览代码
	 * @param vo 数据表配置
	 * @return
	 */
	@ApiOperation(value = "previewCode", notes = "预览代码")
	@GetMapping("/preview")
	public R previewCode(GenConfVO vo) {
		GenConfModel model = GenConfStruct.INSTANCE.to(vo);
		return R.ok(generatorService.previewCode(model));
	}

	/**
	 * 查询表的列信息
	 * @param page 分页
	 * @param vo 数据表配置
	 * @return
	 */
	@ApiOperation(value = "getTable", notes = "查询表的列信息")
	@GetMapping("/table")
	public R getTable(Page page, GenConfVO vo) {
		GenConfModel model = GenConfStruct.INSTANCE.to(vo);
		return R.ok(columnService.listTable(page, model));
	}

	/**
	 * 生成代码
	 * @param vo 数据表配置
	 */
	@Idempotent
	@ApiOperation(value = "generatorCode", notes = "生成代码")
	@SneakyThrows
	@PostMapping("/code")
	public void generatorCode(@RequestBody GenConfVO vo, HttpServletResponse response) {
		GenConfModel model = GenConfStruct.INSTANCE.to(vo);
		byte[] data = generatorService.generatorCode(model);
		response.reset();
		response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
				String.format("attachment; filename=%s.zip", model.getTableName()));
		response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
		response.setContentType("application/octet-stream; charset=UTF-8");

		IoUtil.write(response.getOutputStream(), Boolean.TRUE, data);
	}

}
